<template>
  <el-dialog :title="dialogTitle" v-model="dialogVisible">
    <el-form
      ref="formRef"
      :model="formData"
      :rules="formRules"
      label-width="120px"
      v-loading="formLoading"
    >
      <el-form-item label="文章类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择文章类型">
          <el-option v-for="item in articleTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item>
      <el-form-item label="标题" prop="title">
        <el-input v-model="formData.title" placeholder="请输入标题" />
      </el-form-item>
      <el-form-item label="二级标题" prop="subTitle">
        <el-input v-model="formData.subTitle" placeholder="请输入二级标题" />
      </el-form-item>
      <el-form-item label="描述" prop="mainContent">
        <el-input v-model="formData.mainContent" placeholder="请输入描述" />
      </el-form-item>
      <el-form-item label="内容" prop="content">
        <Editor v-model="formData.content" height="500px" />
      </el-form-item>
      <!-- <el-form-item label="文章类型" prop="type">
        <el-select v-model="formData.type" placeholder="请选择文章类型">
          <el-option v-for="item in articleTypes" :key="item.value" :label="item.label" :value="item.value" />
        </el-select>
      </el-form-item> -->
      <el-form-item label="预览图" prop="mainPhotoPath">
        <MultiUploadImage v-model="formData.mainPhotoPath" />
      </el-form-item>
      <el-form-item label="相关图片" prop="photoPath">
        <MultiUploadImage v-model="formData.photoPath" />
      </el-form-item>
      <el-form-item label="手机端图片" prop="mphotoPath">
        <MultiUploadImage v-model="formData.mphotoPath" />
      </el-form-item>
      <el-form-item label="排序号" prop="sort">
        <el-input v-model="formData.sort" placeholder="请输入排序号" />
      </el-form-item>
      <el-form-item label="是否展示在首页" prop="isShowMain">
        <el-switch v-model="formData.isShowMain" />
      </el-form-item>
      <el-form-item label="状态" prop="status">
        <el-radio-group v-model="formData.status">
          <el-radio v-for="item in statusOptions" :key="item.value" :label="item.value">{{ item.label }}</el-radio>
        </el-radio-group>
      </el-form-item>
    </el-form>
    <template #footer>
      <el-button @click="submitForm" type="primary" :disabled="formLoading">确 定</el-button>
      <el-button @click="dialogVisible = false">取 消</el-button>
    </template>
  </el-dialog>
</template>
<script setup>
import { ArticleApi } from '@/api/article'
import Editor from '@/components/Editor/Editor.vue'
import MultiUploadImage from '@/components/UploadImage/MultiUploadImage.vue'
import { useRoute } from 'vue-router';

/** 所有文章 表单 */
defineOptions({ name: 'ArticleForm' });

// const { t } = useI18n() // 国际化
const message = useMessage() // 消息弹窗
const route = useRoute()

const dialogVisible = ref(false) // 弹窗的是否展示
const dialogTitle = ref('') // 弹窗的标题
const formLoading = ref(false) // 表单的加载中：1）修改时的数据加载；2）提交的按钮禁用
const formType = ref('') // 表单的类型：create - 新增；update - 修改
// 状态选项数组
const statusOptions = ref([
  { label: '开启', value: 1 },
  { label: '删除', value: 2 }
])

// 文章类型数组
const articleTypes = ref([
  { label: '产品亮点', value: 1 },
  { label: '应用安全', value: 2 },
]);

const formData = ref({
  id: undefined,
  title: undefined,
  subTitle: undefined,
  content: undefined,
  type: 1,
  mainPhotoPath: [],
  photoPath: [],
  mphotoPath: [],
  sort: undefined,
  mainContent: undefined,
  status: 1,
  isShowMain: undefined,
})
const formRules = reactive({
  title: [{ required: true, message: '标题不能为空', trigger: 'blur' }],
  content: [{ required: true, message: '内容不能为空', trigger: 'blur' }],
  // type: [{ required: true, message: '文章类型不能为空', trigger: 'change' }],
  // photoPath: [{ required: true, type: 'array', min: 1, message: '至少上传一张相关图片', trigger: 'blur' }],
  // mphotoPath: [{ required: true, type: 'array', min: 1, message: '至少上传一张手机端图片', trigger: 'blur' }]
});
const formRef = ref() // 表单 Ref

/** 打开弹窗 */
const open = async (type, rowData = null) => {
  dialogVisible.value = true
  dialogTitle.value = type === 'create' ? '新增' : '修改'
  formType.value = type
  resetForm()
  // 修改时，直接使用传入的数据
  if (type === 'create') {
    formLoading.value = true
    try {
      formData.value.type = rowData.articleType
      formData.value.articleId = rowData.articleId
      formData.value.title = rowData.title
      formData.value.subTitle = rowData.subTitle
      formData.value.content = rowData.content
    } finally {
      formLoading.value = false
    }
  } else {
    formLoading.value = true
    try {
      // 深拷贝传入的数据，避免直接修改原数据
      formData.value = { 
        ...rowData,
        mainPhotoPath: rowData.mainPhotoPath || []
      }
    } finally {
      formLoading.value = false
    }
  }
}
defineExpose({ open }) // 提供 open 方法，用于打开弹窗

/** 提交表单 */
const emit = defineEmits(['success']) // 定义 success 事件，用于操作成功后的回调
const submitForm = async () => {
  // 校验表单
  await formRef.value.validate()
  // 提交请求
  formLoading.value = true
  try {
    const data = formData.value
    if (formType.value === 'create') {
      await ArticleApi.createArticleItem(data)
      message.success('新增成功')
    } else {
      await ArticleApi.updateArticleItem(data)
      message.success('修改成功')
    }
    dialogVisible.value = false
    // 发送操作成功的事件
    emit('success')
  } finally {
  formLoading.value = false
  }
}

/** 重置表单 */
const resetForm = () => {
  formData.value = {
    id: undefined,
    title: undefined,
    subTitle: undefined,
    content: undefined,
    type: 1,
    mainPhotoPath: [],
    photoPath: [],
    mphotoPath: [],
    sort: undefined,
    mainContent: undefined,
    status: 1,
    isShowMain: undefined,
  }
  // 确保formRef.value存在时才调用resetFields
  if (formRef.value) {
    try {
      formRef.value.resetFields()
    } catch (error) {
      console.warn('表单重置失败:', error)
    }
  }
}

</script>